package br.ufpe.cin.mac.util;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import br.ufpe.cin.mac.middleware.Middleware;


public class ProxyJms implements InvocationHandler {

	private final byte REQUEST = 1;

	private final byte RESPONSE = 2;

	@SuppressWarnings("unused")
	private Class receiver,sender;

	private Object owner;
	
	private Middleware mid;

	private Map buffer;

	public ProxyJms(Object owner,Object receiver, Middleware mid) {
		this.owner = owner;
		this.receiver = (Class)receiver;
		this.mid = mid;
		buffer = Collections.synchronizedMap(new HashMap());
		
	}

	public ProxyJms(Object owner, Middleware mid) {
		this(owner,null,mid);
	}
	
	public Object invoke(final Object proxy, final Method meth,
			final Object[] args) throws Throwable {
		try {
			
			if(FrameworkConstants.JMS_SEND_METHOD.equals(meth.getName())) {
				Message msg = prepareMessage(receiver.getSimpleName(),
						owner.getClass().getSimpleName(), meth, args, REQUEST);
				this.sendMessage(msg, REQUEST);
				
			}
			else if(FrameworkConstants.JMS_GET_METHOD.equals(meth.getName())) {
				
			}
			
			return null;
			
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	
	private Message prepareMessage(String receiver, String sender, Method meth,
			Object[] args, int type) {
		Message msg = new Message(sender, receiver, "Ok");

		msg.setMethod(meth.getName());
		msg.setParameter(args);
		msg.setMsgId(type);

		return msg;
	}

	private void sendMessage(Message msg,byte type) {
		//msg.setType(type);
		
		String swap = msg.getSender();
		msg.setSender(msg.getReceiver());
		msg.setReceiver(swap);
		
	//	mid.send(msg,type);
	}

	public boolean hasMsg(int msgID) {
		return buffer.containsKey(msgID);
	}
}